angular.module('Controller')
.controller 'QgySubLetCheckInCtrl', ($scope, $http, $rootScope,qgyApiService, commonConstant, urls, wfAlert, $uibModal, $localStorage)->
    $scope.sexList = commonConstant.numSexList()
    initData=()->
        if $scope.contractNew
            lastApId=$scope.contractNew?.apartmentId
        $scope.contractNew = {
            apartmentId: lastApId
            buildingId: undefined
            floor: undefined
            houseId: undefined
            payWay: undefined
            lease: undefined
            leaseStart: undefined
            created: false
            sumConsumption:0
        }
        $scope.checkIn = {
            receptionist: undefined
            buzType:1
            contractPicture:undefined
        }
        $scope.dealing={
            create:false
            checkIn:false
        }
        $scope.offLeaseInfo={
            bankName:undefined
            bankAccount:undefined
            bankUser:undefined
        }
        $scope.person = {
            customerName: undefined
            customerPhone: undefined
            customerCard: undefined
            idcardFront: undefined
            idcardBack: undefined
            sex: 1
        }
        $scope.contractData = undefined
        $scope.cotenant = []
    initData()
    $scope.doInit=false
    $scope.reletTypeList=[{value:1,name:'原房'},{value:2,name:'换房'}]
    $scope.newConsumption={
        money:undefined
        description:undefined
    }
    $scope.consumptions=[]
    $scope.apartmentList = []
    $scope.buildingList = [{id: undefined, name: '未选择'}]
    $scope.floorList = [{id: undefined, name: '未选择'}]
    $scope.houseList = [{id: undefined, houseNo: '未选择'}]
    $scope.payWayList = [{value: undefined, name: '--'}]
    $scope.leaseList = [{value: undefined, name: '--'}]
    $scope.offPayTypeList = commonConstant.offPayTypeList()
    $scope.channelTypeList = commonConstant.chiChannelTypeList()
    loadApartment = ()->
        $scope.apartmentList = []
        $http.get('/apartment', params: {page: 0, size: 999, enabled: true})
        .success (resp)->
            if resp.code == 0
                $scope.apartmentList = $scope.apartmentList.concat(resp.message.content)
                if $scope.apartmentList.length > 0 and $scope.contractNew.apartmentId == undefined
                    $scope.contractNew.apartmentId = $scope.apartmentList[0].id
                    $scope.loadBuilding()
            else
                console.log(resp.message)
        .error (err)->
            console.log(err)
    loadApartment()
    refreshSumMoney=()->
        sum1=0
        _.each($scope.consumptions,(item)->
            sum1+=item.money
        )
        $scope.contractNew.sumConsumption=sum1
    _.defer(()->
        $('#sublet-idcard-front').unbind()
        $('#sublet-idcard-front').change(()->
            fileName=$('#sublet-idcard-front').eq(0).val()
            if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileName))
                wfAlert.toastInfo('仅接受图片文件')
                return
            formData = new FormData()
            formData.append('file', $('#sublet-idcard-front')[0].files[0])
            $http({
                url: urls.backend + urls.imageUploadTo + "/image?token=" + $localStorage['token'],
                method: 'POST'
                headers: {
                    'Content-Type': undefined
                }
                data: formData
                transformRequest: angular.identity
            }).success((resp)->
                if resp.code == 0
                    saveUrl = resp.message.saveUrl + ""
                    if(saveUrl.indexOf("http") == 0)
                        $scope.person.idcardFront = saveUrl
                    else
                        $scope.person.idcardFront = urls.backend + '/public/' + saveUrl
            )
        )
        $('#sublet-idcard-back').unbind()
        $('#sublet-idcard-back').change(()->
            fileName=$('#sublet-idcard-back').eq(0).val()
            console.log()
            if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileName))
                wfAlert.toastInfo('仅接受图片文件')
                return
            formData = new FormData()
            formData.append('file', $('#sublet-idcard-back')[0].files[0])
            $http({
                url: urls.backend + urls.imageUploadTo + "/image?token=" + $localStorage['token'],
                method: 'POST'
                headers: {
                    'Content-Type': undefined
                }
                data: formData
                transformRequest: angular.identity
            }).success((resp)->
                if resp.code == 0
                    saveUrl = resp.message.saveUrl + ""
                    if(saveUrl.indexOf("http") == 0)
                        $scope.person.idcardBack = saveUrl
                    else
                        $scope.person.idcardBack = urls.backend + '/public/' + saveUrl
            )
        )
    )
    $scope.$watch('person',(val)->
        $scope.cotenant=qgyApiService.syncCotenantByPersonInfo($scope.person,$scope.cotenant)
    ,true)
    _.extend $scope,
        addConsumption:()->
            sum1=0
            _.each($scope.consumptions,(item)->
                sum1+=item.money
            )
            sum=sum1+$scope.newConsumption.money
            if sum>($scope.subletInfo.returnDeposit)
                wfAlert.toastInfo('扣款总额不能大于应退押金')
                return
            else if sum<($scope.returnInfo.returnDeposit - $scope.contract.deposit)
                wfAlert.toastInfo('通过扣款金额减免押金扣除不能超过已扣除押金')
                return
            $scope.consumptions.push(angular.copy($scope.newConsumption))
            $scope.newConsumption={
                money:undefined
                description:undefined
            }
            refreshSumMoney()
        removeConsumption:(item)->
            $scope.consumptions=_.without($scope.consumptions,item)
            refreshSumMoney()
        uploadIDCFront: ()->
            console.log('uploadIDCFront')
            if !$scope.contractNew.created
                $('input[id=sublet-idcard-front]').click();
            ''
        uploadIDCBack: ()->
            if !$scope.contractNew.created
                $('input[id=sublet-idcard-back]').click();
            ''
        doCancel: ()->
            initData()
            $scope.resetBuilding()
        resetHouse: ()->
            $scope.contractNew.houseId = undefined
            $scope.houseInfo = undefined
            $scope.houseList = [{id: undefined, houseNo: '未选择'}]
            $scope.payWayList = [{value: undefined, name: '--'}]
            $scope.leaseList = [{value: undefined, name: '--'}]
            $scope.contractNew.payType = undefined
        resetBuilding: ()->
            $scope.contractNew.buildingId = undefined
            $scope.resetFloor()
        resetFloor: ()->
            $scope.contractNew.floor = undefined
            $scope.floorList = [{id: undefined, name: '未选择'}]
            $scope.resetHouse()
        loadBuilding: ()->
            return if $scope.doInit
            $scope.buildingList = [{id: undefined, name: '未选择'}]
            reqData = {page: 0, size: 999, apartmentId: $scope.contractNew.apartmentId, sort: 'id,ASC'}
            $http.get('/building', params: reqData)
            .success (resp)->
                if resp.code == 0
                    $scope.buildingList = $scope.buildingList.concat(resp.message.content)
                    $scope.resetBuilding()
        loadFloor: ()->
            return if $scope.doInit
            if $scope.contractNew.buildingId == undefined
                $scope.resetFloor()
            else
                $scope.resetFloor()
                building = _.find($scope.buildingList, (theBd)-> theBd.id == $scope.contractNew.buildingId)
                $scope.floorList = $scope.floorList.concat(building.floorDesc) if building
        loadHouse: ()->
            return if $scope.doInit
            if $scope.contractNew.floor == undefined
                $scope.resetHouse()
                return
            $scope.houseList = [{id: undefined, houseNo: '未选择'}]
            reqData = {
                page: 0, size: 999,
                apartmentId: $scope.contractNew.apartmentId
                buildingId: $scope.contractNew.buildingId
                floor: $scope.contractNew.floor
                status: 1
            }
            $http.get('/house', params: reqData)
            .success (resp)->
                if resp.code == 0
                    $scope.resetHouse()
                    $scope.houseList = $scope.houseList.concat(resp.message.content)
        pickHouse: ()->
            return if $scope.doInit
            if $scope.contractNew.houseId == undefined
                $scope.houseInfo == undefined
                $scope.contractNew.payType = undefined
                $scope.payWayList = [{value: undefined, name: '--'}]
                $scope.leaseList = [{value: undefined, name: '--'}]
            else
                $scope.houseInfo = _.find($scope.houseList, (theRoom)-> theRoom.id == $scope.contractNew.houseId)
                console.log('houseInfo', $scope.houseInfo)
                $scope.payWayList = commonConstant.transferpayWayList($scope.houseInfo.payType)
                $scope.leaseList = commonConstant.leaseList()
                $scope.contractNew.lease = $scope.leaseList[1].value
                if $scope.payWayList.length > 0
                    $scope.contractNew.payWay = $scope.payWayList[0].value
        fetchUser:()->
            if $scope.person.customerPhone?.length==11
                pm=qgyApiService.fetchAsyncUser($scope.person.customerPhone)
                pm.then((data)->
                    $scope.person=data
                )
        offlineCheckIn: ()->
            ''
        offlineCotenant: ()->
            if $scope.contractNew.created
                $scope.openCotenant('view', $scope.cotenant)
            else
                $scope.openCotenant('edit', $scope.cotenant)
        confirmSubLet: ()->
            if $scope.contractNew.payWay == 2 && $scope.contractNew.lease == 1
                wfAlert.toastError('付款方式为押一付三时不允许租期少于三个月')
                return
            if $scope.person.customerPhone == $scope.oriContract.customerPhone
                wfAlert.toastError('转租人手机号不能与原承租人相同')
                return
            if !$scope.person.idcardFront || !$scope.person.idcardBack
                wfAlert.toastError('请上传身份证正反面照片')
                return
            return if $scope.dealing['create']
            $scope.dealing['create']=true
            $scope.contractNew.creating = true
            data = {
#                "houseId": $scope.contractNew.houseId,
#                "payWay": $scope.contractNew.payWay,
#                "lease": $scope.contractNew.lease\
                "money":$scope.subletInfo.returnDeposit-$scope.contractNew.sumConsumption
                "consumptions": $scope.consumptions
                "bankName":$scope.offLeaseInfo.bankName
                "bankAccount":$scope.offLeaseInfo.bankAccount
                "bankUser":$scope.offLeaseInfo.bankUser
                "newCustomerName":$scope.person.customerName
                "newCustomerPhone":$scope.person.customerPhone
                "newCustomerIdCard":$scope.person.customerCard
                "idcardFront": $scope.person.idcardFront,
                "idcardBack": $scope.person.idcardBack
            }
            data['leaseEnd']=moment().format('YYYY-MM-DD') if $scope.contractNew.leaseStart
            $http.put("/contract/#{$scope.oriContract.id}/sublet", data).success((resp)->
                $scope.contractNew.creating = false
                if resp.code == 0
#后台无电子签名步骤，生成合同后直接调确认接口将合同状态置为待入住
                    $scope.billId=resp.message.newBillId
                    console.log('合同生成成功',resp.message)
                    tmp1={"contractPdf":"pdfUrl","signPicture":"signUrl"}
                    $http.put("/contract/confirm/#{resp.message.newContractId}",tmp1)
                    .success((confirmResp)->
                        $scope.dealing['create']=false
                        if confirmResp.code==0
                            $rootScope.$broadcast('refresh')
                            wfAlert.toastInfo('合同生成成功')
                            $scope.contractNew.created = true
                            $scope.loadContract(resp.message.newContractId)
                    )
                    .error((err)->
                        $scope.dealing['create']=false
                    )
                else
                    $scope.dealing['create']=false
                    wfAlert.toastError(resp.message)
            )
        loadContract: (id)->
            return if id == undefined
            $http.get("/contract/#{id}/detail")
            .success((resp)->
                if resp.code == 0
                    $scope.contractData = resp.message
                    console.log('contractData', $scope.contractData)
            )
        changeReLetWay:()->
            if $scope.contractNew.reletType==1
                console.log('刷新回原房')
                loadHouseData(angular.copy($scope.oriHouse))
        subletCheckIn: ()->
            return if $scope.dealing['checkIn']
            $scope.dealing['checkIn']=true
            reqData = {
                "preContractId":$scope.oriContract.id,
                "money":$scope.subletInfo.returnDeposit-$scope.contractNew.sumConsumption
                "consumptions": $scope.consumptions
                "bankName":$scope.offLeaseInfo.bankName
                "bankAccount":$scope.offLeaseInfo.bankAccount
                "bankUser":$scope.offLeaseInfo.bankUser
                "contractPicture":$scope.checkIn.contractPicture
            }
            reqData['leaseEnd']=moment().format('YYYY-MM-DD') if $scope.contractNew.leaseStart
            $http.put("/contract/#{$scope.contractData.id}/sublet/checkIn", reqData)
            .success((resp)->
                $scope.dealing['checkIn']=false
                if resp.code == 0
                    $rootScope.$broadcast('refresh')
                    wfAlert.toastInfo('入住成功')
                    $scope.contractData.status=8
            )
        openCotenant: (type, item)->
            modal = showCotenantModal(type, item)
            modal.result.then((modalData)->
                if modalData && type != 'view'
                    item = modalData
            )
            ''
    showCotenantModal = (type, data)->
        modal = $uibModal.open({
            animation: true,
            size: 'lg',
            appendTo: $("#modalContent:eq(0)"),
            controller: 'QgyCotenantModalCtrl',
            templateUrl: 'templates/business-manage/cotenant-modal/cotenant-modal.html',
            resolve: {
                items: ()-> {type: type, data: data}
            }
        })
    ##由房态管理页面进入时，带入已有的公寓、楼栋、楼层、房间号、房间信息
    loadHouseData = (paramData)->
        $scope.doInit=true
        $scope.contractNew.apartmentId = paramData.apartmentId
        $scope.contractNew.buildingId = paramData.buildingId
        $scope.contractNew.floor = paramData.floor
        $scope.contractNew.houseId = paramData.id
        $scope.contractNew.leaseStart = new Date()
        reqData = {page: 0, size: 999, apartmentId: paramData.apartmentId, sort: 'id,ASC'}
        loadHouse1 = ()->
            houseReqData = {
                page: 0, size: 999
                apartmentId: $scope.contractNew.apartmentId
                buildingId: $scope.contractNew.buildingId
                floor: $scope.contractNew.floor
            }
            $http.get('/house', params: houseReqData)
            .success (resp)->
                if resp.code == 0
                    $scope.houseList = [{id: undefined, name: '未选择'}]
                    houseLs=resp.message.content
                    houseLs=_.filter(houseLs,(theHl)->theHl.status==1 || theHl.id==$scope.contractNew.houseId)
                    $scope.houseList = $scope.houseList.concat(houseLs)
                    $scope.houseInfo = _.find($scope.houseList, (theRoom)-> theRoom.id == $scope.contractNew.houseId)
                    $scope.payWayList = commonConstant.transferpayWayList($scope.houseInfo.payType)
                    $scope.leaseList = commonConstant.leaseList()
                    $scope.contractNew.lease = $scope.leaseList[1].value
                    if $scope.payWayList.length > 0
                        $scope.contractNew.payWay = $scope.payWayList[0].value
                    console.log('注入结果', $scope.contractNew)
                $scope.doInit=false
        $http.get('/building', params: reqData)
        .success (resp)->
            if resp.code == 0
                $scope.buildingList = [{id: undefined, name: '未选择'}]
                $scope.buildingList = $scope.buildingList.concat(resp.message.content)
                $scope.floorList = [{id: undefined, name: '未选择'}]
                building = _.find($scope.buildingList, (theBd)-> theBd.id == $scope.contractNew.buildingId)
                $scope.floorList = $scope.floorList.concat(building.floorDesc)
                loadHouse1()
        ''
    loadSubletData=()->
        return if !$scope.contractNew.leaseStart
        reqData={
            checkOutDate:moment($scope.contractNew.leaseStart).format('YYYY-MM-DD')
        }
        $http.get("/contract/#{$scope.oriContract.id}/sublet/money",params:reqData)
        .success((resp)->
            if(resp.code==0)
                $scope.subletInfo=resp.message
            else
                wfAlert.toastError('换房信息获取异常：',resp.message)
        )
    if $rootScope.pageType == 'sublet-check-in'
        console.log('转租:', $rootScope.pageParams)
        $scope.oriHouse=angular.copy($rootScope.pageParams.house)
        $scope.oriContract=angular.copy($rootScope.pageParams.contract)
        loadHouseData(angular.copy($scope.oriHouse))
        loadSubletData()
        $rootScope.pageParams = undefined
        $rootScope.pageType = undefined
